﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WarOfDev.Core;
using WarOfDev.Core.Common;
using WarOfDev.EF;
using WarOfDev.Services.Common;
using WarOfDev.Services.Developer;
using WarOfDev.Services.Task;
using WarOfDev.Web.ViewModels;

namespace WarOfDev.Web.Controllers
{
    public class TaskController : BaseController
    {
        private readonly WarDevEntities db = new WarDevEntities();
        private readonly TaskService taskService = new TaskService();

        //
        // GET: /Task/

        public ActionResult Index()
        {
            


            var ret = from t in db.Tasks
                      join assignment in db.AssignedTasks on t.Id equals assignment.TaskId
                      join developer in db.Developers on assignment.DevId equals developer.Id
                      into task
                      from d in task.DefaultIfEmpty() 
                      select new TaskViewModel() {
                        DeveloperId=assignment.DevId,
                        DeveloperName=d.NickName,
                        
                        AssignmentID=assignment.Id,
                        CreatedBy=t.CreatedBy,
                        CreatedOn=t.CreatedOn,
                        Description=t.Description,
                        Status=t.Status,
                        ExperienceValue=t.ExperienceValue,
                        Id=t.Id,
                        ModifiedBy=t.ModifiedBy,
                        ModifiedOn=t.ModifiedOn,
                        //Status=assignment.Status,
                        Title=t.Title
                      };

            return View(ret);
        }

        //
        // GET: /Task/Details/5

        public ActionResult Details(string id)
        {
            Task task = db.Tasks.Single(t => t.Id == id);
            if (task == null)
            {
                return HttpNotFound();
            }
            return View(task);
        }

        //
        // GET: /Task/Create

        public ActionResult Create()
        {

            var model = new TaskViewModel();
            model.AllDeveloperList = WarOfDev.Services.Developer.DeveloperService.GetAllDeveloperList(string.Empty);
            
            return View(model);
        }

        //
        // POST: /Task/Create

        [HttpPost]
        public ActionResult Create(TaskViewModel task)
        {
            if (ModelState.IsValid)
            {
                Task dbTask = task.ToModel();

                dbTask.CreatedBy = dbTask.ModifiedBy=  this.CurrentUser.Id;
                var assignment = dbTask.Assignment.ToList()[0];
                assignment.CreatedBy = assignment.ModifiedBy = this.CurrentUser.Id;

                db.Tasks.AddObject(dbTask);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(task);
        }

        [HttpGet]
        public ActionResult My()
        {
            var taskIds= db.AssignedTasks.Where(a => a.DevId == this.CurrentUser.Id).Select(a=>a.TaskId).ToList();
            var mytasks = db.Tasks.Include("Assignment").Include("Assignment.Developer").Where(t => taskIds.Contains(t.Id)).ToList().Select(t=>new TaskViewModel(t));



            return View("Index", mytasks);
            
        }

        //
        // GET: /Task/Edit/5

        public ActionResult Edit(string id)
        {
            Task task = db.Tasks.Include("Assignment").Single(t=>t.Id==id);
            if (task == null)
            {
                return HttpNotFound();
            }

            var taskViewMode = new TaskViewModel(task);
            var taskStatus = task.Assignment.ToList()[0].Status.ToString();


            var owner=string.Empty;
            if (task.Assignment != null && task.Assignment.Count > 0)
            {
                owner = task.Assignment.ToList()[0].DevId;
            }

            taskViewMode.AllDeveloperList = DeveloperService.GetAllDeveloperList(owner);

            taskViewMode.TaskStatusList= (from item in db.GroupItems.AsEnumerable()
                                         where item.GroupId==ConstItemGroup.TaskStatus
                                         select new SelectListItem()
                                         {
                                            Text=item.ItemName,
                                            Value=item.ItemValue,
                                            Selected= taskStatus == item.ItemValue

                                         }).ToList();

            return View(taskViewMode);
        }



        //
        // POST: /Task/Edit/5

        [HttpPost]
        public ActionResult Edit(TaskViewModel task)
        {
            if (ModelState.IsValid)
            {
                Task dbTask = new Task() { Id=task.Id};
                db.Tasks.Attach(dbTask);
                dbTask.Assignment.Load();
                
                dbTask.ExperienceValue = task.ExperienceValue;
                dbTask.Title = task.Title;
                dbTask.Description = task.Description;
                dbTask.Assignment.ToList()[0].DevId = task.DeveloperId;
                dbTask.ModifiedOn = DateTime.Now;
                dbTask.Status = task.Status;

                if (dbTask.Status == (int)EnumTaskStatus.Closed)
                {
                    dbTask.Assignment.ToList().ForEach(a =>
                            a.Developer.ExperienceValue+=task.ExperienceValue    
                        );
                }

                db.SaveChanges();
                
                return RedirectToAction("Index");
            }
            return View(task);
        }

        //
        // GET: /Task/Delete/5

        public ActionResult Delete(string id )
        {
            Task task = db.Tasks.Single(t => t.Id == id);
            if (task == null)
            {
                return HttpNotFound();
            }
            return View(task);
        }

        //
        // POST: /Task/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            Task task = db.Tasks.Single(t => t.Id == id);
            db.Tasks.DeleteObject(task);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }


        


        [ChildActionOnly]
        [ActionName("TaskExperienceValueCollectionHasDefaultValue")]
        public ActionResult TaskExperienceValueCollection(int defaultValue)
        {
            List<SelectListItem> collection= 
                ExperienceValueCollectionCreator.GetExperienceValueCollection(new TaskExperienceValueCollectionCreator(defaultValue));

            return PartialView("TaskExperienceValueList", collection);  
        }

        [ChildActionOnly]
        public ActionResult TaskExperienceValueCollection()
        {
            List<SelectListItem> collection =
                ExperienceValueCollectionCreator.GetExperienceValueCollection(new TaskExperienceValueCollectionCreator());

            return PartialView("TaskExperienceValueList", collection);
        }
        
        
    }
}